package com.xxwy.ddu.security.browser.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxwy.ddu.security.code.properties.LoginResponseType;
import com.xxwy.ddu.security.code.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author xxwy
 * on 2018/8/20 0020
 * 登录失败
 */
@Slf4j
@Component
public class BrowserAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException, ServletException {

        logger.info("登录失败");
        if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            HashMap<String, Object> map = new HashMap<>();
            map.put("body",e.getMessage());
            response.getWriter().write(map.toString());
        }else{
            super.onAuthenticationFailure(request, response, e);
        }
    }
}
